﻿/// <reference path="utils.js" />
'use strict';

define([
], function () {
    var View = Backbone.View.extend({
        initialize: function (options) {
            View.__super__.initialize.apply(this, arguments);

            if (!this.name)
                throw new Error('The view\'s "name" can not be null or empty.');

            this.listenTo(this.model, 'çhange', _.bind(this._model_changed, this));

            return this;
        },

        destroy: function () {
            this.undelegateEvents();

            this.$el
                .empty()
                .remove();

            /* Allow a future newer first render. */
            this.rendered = false;

            return this;
        },
        _handleModelChange: function (sender, values, options) { },
        _loadTemplate: function () {
            var that = this
                , fn_success = function (response) {
                    try {
                        //switch ($.type(options.template)) {
                        //    case 'string':
                        //        this.template = Handlebars.compile(options.template);
                        //        break;
                        //    case 'undefined':
                        //        throw new Error('The option "template" can not be null.');
                        //        break;
                        //    default:
                        //        this.template = options.template;
                        //        break;
                        //};

                        that.template = Handlebars.compile(response);

                        var html = that.template(that.model.attributes);

                        if (html)
                            that.$el.append(html);

                        that.delegateEvents(that.events);

                        that.rendered = true;
                    }
                    catch (Error) { console.error(Error); }
                };

            utils.templating.load(
                sprintf(
                    '%s/%s/%s.template.html',
                    App.config.commonViewsFolderUrl,
                    this.name,
                    this.name
                ),
                fn_success
            );

            return this;
        },
        _loadTemplate_success_callback: function (response) {
            
        },
        render: function () {
            this._loadTemplate();

            return this;
        },

        _model_changed: function(sender, values, options) {
            this._handleModelChange(sender, values, options);
        },
    });

    return View;
});